package ica_alink

import (
	"encoding/json"
	"fmt"
	"github.com/shopspring/decimal"
	"time"
)

// PropertyReportAsk 属性上报
type PropertyReportAsk struct {
	BaseAsk
	Params map[string]ReportDataItem `json:"params"`
}

func (ask *PropertyReportAsk) AddParam(key string, value interface{}) {
	if ask.Params == nil {
		ask.Params = map[string]ReportDataItem{}
	}
	ask.Params[key] = ReportDataItem{
		Time:  time.Now().UnixMilli(),
		Value: value,
	}
}

type ReportDataItem struct {
	Time  int64       `json:"time"` //毫秒级
	Value interface{} `json:"value"`
}

func (item ReportDataItem) ReportDataItemValueString() string {
	return item.ValueString(item.Value)
}

func (item ReportDataItem) ValueString(v interface{}) string {
	return ReportValueString(v)
}

func ReportValueString(v interface{}) string {
	if tmp, ok := v.(map[string]interface{}); ok {
		s, _ := json.Marshal(tmp)
		return string(s)
	}
	if tmp, ok := v.([]interface{}); ok {
		s, _ := json.Marshal(tmp)
		return string(s)
	}
	if tmp, ok := v.(float64); ok {
		//直接用 decimal.NewFromFloat64(tmp).String() 还是会有部分场景下的精度问题
		b, _ := decimal.NewFromString(fmt.Sprintf("%f", tmp))
		return b.String()
	}
	if tmp, ok := v.(int64); ok {
		return decimal.NewFromInt(tmp).String()
	}
	if tmp, ok := v.(int); ok {
		return decimal.NewFromInt(int64(tmp)).String()
	}

	return fmt.Sprint(v)
}

type PropertyReportReply struct {
	BaseReply
	Data interface{} `json:"data"`
}

func ItemValueString(item interface{}) string {
	if tmp, ok := item.(map[string]interface{}); ok {
		s, _ := json.Marshal(tmp)
		return string(s)
	}
	return fmt.Sprint(item)
}
